package ws.performancetest.app.console;

import com.microsoft.sqlserver.jdbc.SQLServerDriver;
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Collections;
import java.util.List;
import java.util.ServiceLoader;
import ws.performancetest.api.TestSuite;
import ws.performancetest.tests.jdbcdriver.runnable.ResultSetRunnable;
import ws.utils.jdbc.DBConnection;

/**
 *
 * @author Wilson Santos, 36228 <wilson.santos@ua.pt>
 */
public class Application {

  static String server, port, database, username, password;
  static int delayms;

  /**
   * @param args the command line arguments
   */
  public static void main(String[] args) throws Exception {
    boolean connected = false;

    BufferedReader is = new BufferedReader(new FileReader("CONF/login.txt"));

    server = is.readLine();
    port = is.readLine();
    database = is.readLine();
    username = is.readLine();
    password = is.readLine();
    delayms = Integer.parseInt(args[1]);

    List<Driver> jdbcdrivers = Collections.list(DriverManager.getDrivers());
    for (Driver driver : jdbcdrivers) {
      if (driver instanceof SQLServerDriver) {
        connected = DBConnection.setDBUrl(driver, server, port, database, username, password);
      }
    }
    if (!connected) {
      System.err.println("Error connecting to SQL Server");
      System.exit(1);
    }
    runTestSuite(args[0]);
  }

  /**
   * Find the Test Suites on the classpath.
   *
   * @return list with the test suites found.
   */
  public static void runAllTestSuites() throws Exception {
    ServiceLoader<TestSuite> testSuiteProvider = ServiceLoader.load(ws.performancetest.api.TestSuite.class);
    for (TestSuite ts : testSuiteProvider) {
      ts.runAllTests();
    }
  }

  /**
   * Find the Test Suite on the classpath with {@code name}.
   *
   * @param name name of the test suite to run.
   *
   * @return list with the test suites found.
   */
  public static void runTestSuite(String name) throws Exception {
    ServiceLoader<TestSuite> testSuiteProvider = ServiceLoader.load(ws.performancetest.api.TestSuite.class);
    for (TestSuite ts : testSuiteProvider) {
      if (ts.toString().equals(name)) {
        ResultSetRunnable.setDelay(delayms);
        System.out.println("Running '" + name + "' with " + ResultSetRunnable.getDelay() + "ms delay.");
        ts.setDBUrl(DBConnection.getDBUrl());
        ts.setThreadAmountList(new Integer[]{10, 30, 50, 70, 90});
        ts.setCycleAmountList(new Integer[]{35, 65, 95});
        ts.setSamplesCount(30);
        ts.runAllTests();
        break;
      }
    }
  }
}
